# Contributor: Rasmus Thomsen <oss@cogitri.dev>
# Contributor: Jakub Jirutka <jakub@jirutka.cz>
# Contributor: Shiz <hi@shiz.me>
# Contributor: Jeizsm <jeizsm@gmail.com>
# Contributor: Ariadne Conill <ariadne@dereferenced.org>
# Maintainer: Jakub Panek <me@panekj.dev>
pkgname=rust
pkgver=1.72.1
_llvmver=16
_bootver=1.70.0
pkgrel=0
pkgdesc="Rust Programming Language toolchain"
url="https://www.rust-lang.org/"
arch="all"
license="Apache-2.0 AND MIT"

# 'cc' is needed at runtime just for linking. Someday rustc might invoke
# the linker directly, and then we'll only need 'ld'.
# See: https://github.com/rust-lang/rust/issues/11937
depends="gcc musl-dev"

# * Rust is self-hosted, so you need rustc (and cargo) to build rustc...
#   The last revision of this abuild that does not depend on itself (uses
#   prebuilt rustc and cargo) is 2e6769eb39eaff3029d8298fc02856623c563cd8.
# * Don't add libgit2-dev into make dependencies. There's no compatibility
#   guarantees between libgit2-sys and arbitrary system libgit2 versions;
#   when system libgit2 is upgraded to a new minor version, it may break
#   cargo and since we need cargo to rebuild cargo... this already happened
#   several times. For this reason we build cargo with vendored libgit2.
makedepends_build="
	!libgit2-dev
	cargo-bootstrap=>$_bootver
	coreutils
	curl-dev
	file
	libssh2-dev
	llvm$_llvmver-dev
	llvm$_llvmver-test-utils
	openssl-dev
	python3
	rust-bootstrap>=$_bootver
	tar
	wasi-libc
	xz-dev
	zlib-dev
	"
makedepends_host="
	curl-dev
	libssh2-dev
	llvm$_llvmver-dev
	openssl-dev
	zlib-dev
	"

# XXX: This is a hack to allow this abuild to depend on itself. Adding "rust"
# to makedepends would not work, because abuild implicitly removes $pkgname
# and $subpackages from the abuild's dependencies.
provides="rust-bootstrap=$pkgver-r$pkgrel"
# This is needed for -src that contains some testing binaries.
options="!archcheck"

case "$CARCH" in
armhf|armv7|riscv64)
	# +crt-static still broken here.
	options="$options !check"
	;;
*)
	;;
esac

subpackages="
	$pkgname-dbg
	$pkgname-wasm
	$pkgname-gdb::noarch
	$pkgname-lldb::noarch
	$pkgname-clippy
	$pkgname-doc
	$pkgname-src::noarch
	cargo
	cargo-bash-completions:_cargo_bashcomp:noarch
	cargo-zsh-completion:_cargo_zshcomp:noarch
	cargo-doc:_cargo_doc:noarch
	rustfmt
	"
source="https://static.rust-lang.org/dist/rustc-$pkgver-src.tar.xz
	alpine-move-py-scripts-to-share.patch
	alpine-target.patch
	do-not-install-libunwind-source.patch
	gcc-eh-libunwind.patch
	install-template-shebang.patch
	lfs64-libc.patch.noauto
	lfs64-rust.patch
	libc-s390x-olargefile.patch.noauto
	musl-fix-linux_musl_base.patch
	need-rpath.patch
	need-ssp_nonshared.patch
	no-export-ld-library-path.patch
	system-wasm-ld.patch
	check-rustc
	"
builddir="$srcdir/rustc-$pkgver-src"

# secfixes:
#   1.71.1-r0:
#     - CVE-2023-38497
#   1.66.1-r0:
#     - CVE-2022-46176
#   1.56.1-r0:
#     - CVE-2021-42574
#   1.52.1-r1:
#     - CVE-2021-29922
#   1.51.0-r2:
#     - CVE-2020-36323
#     - CVE-2021-31162
#   1.34.2-r0:
#     - CVE-2019-12083
#   1.26.0-r0:
#     - CVE-2019-16760

if [ -z "$BOOTSTRAP" ]; then
	makedepends_build="
		$makedepends_build
		patchelf
		"
	makedepends_host="
		$makedepends_host
		scudo-malloc
		"
fi

# We have to add new arches in multiple steps:
# 1. Compile with the upstream triplets, compiling alpine's triplets in
# 2. Compile again, now with our triplets selected as build/target, now that
#    rustc knows about them
_build="$CBUILD"
_target="$CTARGET"

_rlibdir="usr/lib/rustlib/$_target/lib"
_sharedir="usr/share/rust"

ldpath="/$_rlibdir"

export OPENSSL_NO_VENDOR=1
export RUST_BACKTRACE=1

# rust checksums files in vendor/, but we have to patch a few files...
_clear_vendor_checksums() {
	sed -i 's/\("files":{\)[^}]*/\1/' vendor/$1/.cargo-checksum.json
}

prepare() {
	default_prepare

	_clear_vendor_checksums libc
	_clear_vendor_checksums libc-0.2.138
	_clear_vendor_checksums libc-0.2.140
	_clear_vendor_checksums libc-0.2.141
	_clear_vendor_checksums libc-0.2.146

	patch -Np1 -d vendor/libc-0.2.138 < "$srcdir"/lfs64-libc.patch.noauto
	patch -Np1 -d vendor/libc-0.2.140 < "$srcdir"/lfs64-libc.patch.noauto
	patch -Np1 -d vendor/libc-0.2.141 < "$srcdir"/lfs64-libc.patch.noauto

	patch -Np1 -d vendor/libc-0.2.138 < "$srcdir"/libc-s390x-olargefile.patch.noauto
	patch -Np1 -d vendor/libc-0.2.140 < "$srcdir"/libc-s390x-olargefile.patch.noauto
	patch -Np1 -d vendor/libc-0.2.141 < "$srcdir"/libc-s390x-olargefile.patch.noauto
}

build() {
	if [ "$_build" != "$_target" ]; then
		export PKG_CONFIG_ALLOW_CROSS=1
	fi

	# absolutely do not set these here, rust "knows" what it's doing
	unset CARGO_PROFILE_RELEASE_LTO
	unset CARGO_PROFILE_RELEASE_OPT_LEVEL
	unset CARGO_PROFILE_RELEASE_PANIC
	unset CARGO_PROFILE_RELEASE_CODEGEN_UNITS

	export CFLAGS="$CFLAGS -O2"
	export CXXFLAGS="$CXXFLAGS -O2"

	case "$CARCH" in
	riscv64)
		;;
	*)
		local lto=--set="rust.lto=thin"
		;;
	esac

	case "$CARCH" in
	aarch64|ppc64le|x86_64)
		# this doesn't build on s390x, but since it's only useful with rust-analyzer,
		# and we enable it on these arches only, just do that
		local rust_analyzer="rust-analyzer-proc-macro-srv,"
		;;
	*)
		local rust_analyzer=""
		;;
	esac

	./configure \
		--build="$_build" \
		--host="$_target" \
		--target="$_target,wasm32-wasi,wasm32-unknown-unknown" \
		--prefix="/usr" \
		--release-channel="stable" \
		--enable-local-rust \
		--local-rust-root="/usr" \
		--llvm-root="/usr/lib/llvm$_llvmver" \
		--disable-docs \
		--enable-extended \
		--tools="cargo,clippy,src,${rust_analyzer}rustdoc,rustfmt,rust-demangler" \
		--enable-llvm-link-shared \
		--enable-option-checking \
		--enable-locked-deps \
		--enable-profiler \
		--enable-vendor \
		--dist-compression-formats=gz \
		--python="python3" \
		--set="rust.musl-root=/usr" \
		--set="rust.backtrace-on-ice=true" \
		--set="rust.codegen-units=1" \
		--set="rust.codegen-units-std=1" \
		--set="rust.deny-warnings=false" \
		--set="rust.parallel-compiler=false" \
		--set="rust.remap-debuginfo=true" \
		--set="rust.description=Alpine Linux $pkgver-r$pkgrel" \
		$lto \
		--set="target.$_target.llvm-config=/usr/lib/llvm$_llvmver/bin/llvm-config" \
		--set="target.$_target.musl-root=/usr" \
		--set="target.$_target.crt-static=false" \
		--set="target.$_target.cc=${CROSS_COMPILE}cc" \
		--set="target.$_target.cxx=${CROSS_COMPILE}c++" \
		--set="target.$_target.ar=${CROSS_COMPILE}ar" \
		--set="target.$_target.linker=${CROSS_COMPILE}cc" \
		--set="target.$_build.musl-root=/usr" \
		--set="target.$_build.crt-static=false" \
		--set="target.$_build.cc=cc" \
		--set="target.$_build.cxx=c++" \
		--set="target.$_build.ar=ar" \
		--set="target.$_build.linker=cc" \
		--set="target.wasm32-unknown-unknown.sanitizers=false" \
		--set="target.wasm32-unknown-unknown.profiler=false" \
		--set="target.wasm32-unknown-unknown.linker=lld" \
		--set="target.wasm32-wasi.sanitizers=false" \
		--set="target.wasm32-wasi.profiler=false" \
		--set="target.wasm32-wasi.wasi-root=/usr/share/wasi-sysroot"

	python3 ./x.py dist --jobs ${JOBS:-2}
}

check() {
	# At this moment lib/rustlib/$CTARGET/lib does not contain a complete
	# copy of the .so libs from lib (they will be copied there during
	# 'x.py install'). Thus we must set LD_LIBRARY_PATH for tests to work.
	# This is related to change-rpath-to-rustlib.patch.

	msg "Setting up test env..."

	mkdir -p "$builddir/test-rustc"

	tar -I "$(command -v pigz || echo gzip) -d" -xf "$builddir"/build/dist/rustc-$pkgver-$_target.tar.gz \
		-C "$builddir/test-rustc" --strip-components=2 --exclude=manifest.in --no-same-owner &
	tar -I "$(command -v pigz || echo gzip) -d" -xf "$builddir"/build/dist/rust-std-$pkgver-$_target.tar.gz \
		-C "$builddir/test-rustc" --strip-components=2 --exclude=manifest.in --no-same-owner &
	wait

	export LD_LIBRARY_PATH="$builddir/test-rustc/lib/rustlib/$CTARGET/lib"

	msg "Sanity checks..."
	"$srcdir"/check-rustc "$builddir"/test-rustc/bin/rustc

	# XXX: There's some problem with these tests, we will figure it out later.
	#	make check \
	#		LD_LIBRARY_PATH="$_stage0dir/lib" \
	#		VERBOSE=1

	# these rebuild the whole compiler which takes a long time
	# msg "Running tests for cargo..."
	# CFG_DISABLE_CROSS_TESTS=1 python3 ./x.py test --no-fail-fast src/tools/cargo

	unset LD_LIBRARY_PATH
}

package() {
	# merged into main package
	provides="$provides rust-stdlib=$pkgver-r$pkgrel"
	replaces="rust-stdlib"

	mkdir -p "$pkgdir/usr"

	cd "$pkgdir"

	tar -I "$(command -v pigz || echo gzip) -d" -xf "$builddir"/build/dist/rustc-$pkgver-$_target.tar.gz \
		-C "$pkgdir/usr" --strip-components=2 --exclude=manifest.in --no-same-owner &
	tar -I "$(command -v pigz || echo gzip) -d" -xf "$builddir"/build/dist/rust-std-$pkgver-$_target.tar.gz \
		-C "$pkgdir/usr" --strip-components=2 --exclude=manifest.in --no-same-owner &
	tar -I "$(command -v pigz || echo gzip) -d" -xf "$builddir"/build/dist/rustc-dev-$pkgver-$_target.tar.gz \
		-C "$pkgdir/usr" --strip-components=2 --exclude=manifest.in --no-same-owner &
	tar -I "$(command -v pigz || echo gzip) -d" -xf "$builddir"/build/dist/rust-src-$pkgver.tar.gz \
		-C "$pkgdir/usr" --strip-components=2 --exclude=manifest.in --no-same-owner &
	wait
	tar -I "$(command -v pigz || echo gzip) -d" -xf "$builddir"/build/dist/cargo-$pkgver-$_target.tar.gz \
		-C "$pkgdir/usr" --strip-components=2 --exclude=manifest.in --no-same-owner &
	tar -I "$(command -v pigz || echo gzip) -d" -xf "$builddir"/build/dist/clippy-$pkgver-$_target.tar.gz \
		-C "$pkgdir/usr" --strip-components=2 --exclude=manifest.in --no-same-owner &
	tar -I "$(command -v pigz || echo gzip) -d" -xf "$builddir"/build/dist/rustfmt-$pkgver-$_target.tar.gz \
		-C "$pkgdir/usr" --strip-components=2 --exclude=manifest.in --no-same-owner &
	tar -I "$(command -v pigz || echo gzip) -d" -xf "$builddir"/build/dist/rust-std-$pkgver-wasm32-unknown-unknown.tar.gz \
		-C "$pkgdir/usr" --strip-components=2 --exclude=manifest.in --no-same-owner &
	tar -I "$(command -v pigz || echo gzip) -d" -xf "$builddir"/build/dist/rust-std-$pkgver-wasm32-wasi.tar.gz \
		-C "$pkgdir/usr" --strip-components=2 --exclude=manifest.in --no-same-owner &
	wait

	# We don't want to include stuff like rust-llvm-* tools, as we will use the
	# system tools.
	rm -f usr/lib/rustlib/"$_target"/bin/rust-llvm-*

	# Python scripts are noarch, so move them to /usr/share.
	# Requires move-py-scripts-to-share.patch to be applied.
	_mv usr/lib/rustlib/etc/*.py $_sharedir/etc/
	rmdir -p usr/lib/rustlib/etc 2>/dev/null || true

	_mv usr/etc/bash_completion.d/cargo usr/share/bash-completion/completions/
	rmdir -p usr/etc/bash_completion.d 2>/dev/null || true

	_mv usr/lib/rustlib/src/rust usr/src/
	ln -s ../../../src/rust usr/lib/rustlib/src/rust

	# Remove some clutter.
	cd "$pkgdir"/usr/lib/rustlib
	rm -f components install.log manifest-* rust-installer-version uninstall.sh
	if [ "$_build" != "$_target" ]; then
		rm -rf "$pkgdir"/usr/lib/rustlib/$_build
	fi

	# for some reason the tar archive gets some root-only files for rlibs
	find "$pkgdir"/usr/lib/rustlib -type f -perm -600 -exec chmod 644 {} \+
	find "$pkgdir"/usr/lib/rustlib -type f -perm -700 -exec chmod 755 {} \+

	if [ -z "$BOOTSTRAP" ]; then
		# link scudo to tools by default on architectures where it works well
		# this is roughly 20+% faster with no downside except slightly higher
		# memory use, but this is a compiler that already uses a ton of memory
		case "$CARCH" in
		arm*) ;;
		*)
			patchelf --add-needed libscudo.so \
				"$pkgdir"/usr/bin/cargo \
				"$pkgdir"/usr/bin/rustc \
				"$pkgdir"/usr/bin/rustdoc
			;;
		esac
	fi
}

wasm() {
	pkgdesc="WebAssembly targets for rust"
	depends="rust=$pkgver-r$pkgrel lld wasi-libc"

	amove usr/lib/rustlib/wasm32-*
}

analysis() {
	pkgdesc="Compiler analysis data for the Rust standard library"
	depends="$pkgname=$pkgver-r$pkgrel"

	amove $_rlibdir/../analysis
}

gdb() {
	pkgdesc="GDB pretty printers for Rust"
	depends="$pkgname=$pkgver-r$pkgrel gdb"

	amove usr/bin/rust-gdb*
	amove $_sharedir/etc/gdb_*.py
}

lldb() {
	pkgdesc="LLDB pretty printers for Rust"
	depends="$pkgname=$pkgver-r$pkgrel lldb py3-lldb"

	amove usr/bin/rust-lldb
	amove $_sharedir/etc/lldb_*.py
}

clippy() {
	pkgdesc="Lints to catch common mistakes and improve your Rust code"
	depends="$pkgname=$pkgver-r$pkgrel"

	amove usr/bin/cargo-clippy
	amove usr/bin/clippy-driver
}

src() {
	pkgdesc="$pkgdesc (source code)"
	depends="$pkgname=$pkgver-r$pkgrel"
	license="$license OFL-1.1 GPL-3.0-or-later GPL-3.0-with-GCC-exception CC-BY-SA-3.0 LGPL-3.0"

	amove usr/src
	amove usr/lib/rustlib/src
}

cargo() {
	pkgdesc="The Rust package manager"
	license="Apache-2.0 MIT UNLICENSE"
	depends="$pkgname=$pkgver-r$pkgrel"
	# XXX: See comment on top-level provides=.
	provides="cargo-bootstrap=$pkgver-r$pkgrel"

	amove usr/bin/cargo
	amove usr/libexec/cargo-credential-1password
}

rustfmt() {
	pkgdesc="Rust Code Formatter"
	license="Apache-2.0"
	depends="cargo=$pkgver-r$pkgrel"

	amove usr/bin/rustfmt
	amove usr/bin/cargo-fmt
}

_cargo_bashcomp() {
	pkgdesc="Bash completions for cargo"
	license="Apache-2.0 MIT"
	depends=""
	install_if="cargo=$pkgver-r$pkgrel bash-completion"

	amove usr/share/bash-completion
}

_cargo_zshcomp() {
	pkgdesc="ZSH completions for cargo"
	license="Apache-2.0 MIT"
	depends=""
	install_if="cargo=$pkgver-r$pkgrel zsh"

	amove usr/share/zsh/site-functions/_cargo
}

_cargo_doc() {
	pkgdesc="The Rust package manager (documentation)"
	license="Apache-2.0 MIT"
	install_if="docs cargo=$pkgver-r$pkgrel"

	# XXX: This is hackish!
	cd "$pkgdir"/../$pkgname-doc
	_mv usr/share/man/man1/cargo* "$subpkgdir"/usr/share/man/man1/
}

_mv() {
	local dest; for dest; do true; done  # get last argument
	mkdir -p "$dest"
	mv "$@"
}

sha512sums="
08232b5bf36f82a995d67f3d03d5e35b7d8914d31fb4491d4c37b72a830bc438e9d18d9e138d398b1b6ae4aa09f7f8e1e9b68da6273ab74bdae4c6123586a21b  rustc-1.72.1-src.tar.xz
9de9d7ad05584e3cafddedcac409a4605a1d67e82260220deb3efd965603ee3148062b081c0cd736e50d82daad3a723fb6a7493fdf4dddfe36288645425a7946  alpine-move-py-scripts-to-share.patch
a97bc511a8fd5f71ea7095efa4cf97048badc4ba46d1bde1b7d5ede2879f099157b8b6f5a03278c9f5766d809ea5d6a1affadce7ceb47d0cc134fde8bc70d51d  alpine-target.patch
7af23c34096f7a03c5a1b40aa07e00dd6193743c872881018a9baa900f240c6e44918e481ab5ed7787a70ef361e4aeec2a7719bcd695f52988262e23271b44e5  do-not-install-libunwind-source.patch
92916225c21742941aaf415d75d330fe2baf77a8226c076e862f4413068d5dee7b08c4b3182f69957ea9a51a0dcde145031565289015b6e3c31894fb396e4eb1  gcc-eh-libunwind.patch
2df372bbf9b8c58c2e2ff69cb48ef8b2046710b7f0762e3bf64443298a5973d463227881247aa7a5c31b39e689035ae6283d5f3a209c8dd5d8a39aa0ab3e9a9a  install-template-shebang.patch
8d7236bfe583915be81c28b8b6296d69a7dda0246bd0d294298659825fbffcb4fa21c5ad01c351d358f269a620f3c59b9e7be77cd73a5214cc32ba15efa2fb0d  lfs64-libc.patch.noauto
6a15ea16acaa15a57e8c0f6ae4ccf3e91c6f395249fb2186766642131ee5d37ecf04ade829e1712dce77684b77a54caa6b4356416dd1d3a6832187332531381f  lfs64-rust.patch
aa81a1202a0ab45cb3e52c6caa9acf1fae592affaa925cff79601a65396a81f1e40715872c0d19a12edbf841282b6f263e986b566e3860d7e78ffa9bf49b8bc5  libc-s390x-olargefile.patch.noauto
47d070ccac8d2260b2aa46758aad263e8c7dc4ecc68fcee4619e89089f300c49a050524a241b5c3b32711823fcc062a793aca80e669d7d79395782d1823dba8a  musl-fix-linux_musl_base.patch
2d401a01d2c2db92624d672018342907a41aa4a3842708c0a2ab694af0396d568aca4835d1075f244d77c0a4c45e67f893fd175fd97cd7f758090eba9972eba6  need-rpath.patch
bceb500942913d1a01a764dc7ee35437e83b9aec3f945c9186396264df240f465e5ac4d1f70e7252ca4ec346ffaf7c79747ba1a53ff4123cbd408cfa5effa214  need-ssp_nonshared.patch
cbdb38a2701e079d362e76ff16a2549230f80bcb4dfd3561d240df331fb21d202cb720e18b97fe9b166db1f79b46fab949ce5de5e37af2ed78a10c7fe1dfcfc9  no-export-ld-library-path.patch
4ea59b28fa238b8bb0cb24847e5884b65beec5168e55fe41a1ff50e272f1cf49186ffaa71d133cebfdcb70901ea18b477d7618a1dd330ff6c08bed5af0e2bb78  system-wasm-ld.patch
c31fdfe8a9b3411576c75da46645cf0465b9053000a2ab49cf9b2f2733f679d6d33acbf236d67a20e14935d094a685453b7f1840180249f39d610fd0902c3125  check-rustc
"
